/**
 * @export
 * @class Ground
 * @classdesc 地面
 * @property {Object} 地图容器 - SchoolLab实例
 * @property {String} name - 名称
 * @property {String} color - 颜色
 * @property {Number} opacity - 透明度
 * @property {Number} radius - 半径
 * @property {Number} renderOrder - 层叠顺序
 * @example
 * var ground = new Ground(viewer, {
 *   radius: 4,
 *   color: '#ff0000',
 *   opacity: 0.5,
 *   renderOrder: 20,
 *   name: 'ground'
 * })
 */
import { extend } from './util'
import { EARTH_RADIUS } from './Constant'
import Feature from './Feature'
export default class Ground {
  constructor(viewer, options) {
    const opts = extend({
      name: "ground",
      color: "#172437",
      opacity: 1,
      radius: EARTH_RADIUS * 4,
      renderOrder: 1
    }, options)


    /** @member {SchoolLab} - 地图容器 */
    this.viewer = viewer
    
    /** @member {String} - 名称 */
    this.name = opts.name
    
    /** @member {Color} - 颜色 */
    this.color = opts.color
    
    /** @member {Number} - 透明度 */
    this.opacity = opts.opacity
    
    /** @member {Number} - 半径 */
    this.radius = opts.radius
    
    /** @member {Number} - 层叠顺序 */
    this.renderOrder = opts.renderOrder
    
    /** @member {THREE.Mesh} - mesh对象 */
    this.entity = null

    Feature.apply(this)

    this._init()
  }

  _init() {
    let geometry = this._initGeometry()
    let material = this._initMaterial()
    
    const mesh = new THREE.Mesh(geometry, material)
    mesh.name = this.name
    mesh.renderOrder = this.renderOrder
    
    this.entity = mesh
    this.viewer.world.add(mesh)
  }

  // 初始化几何体
  _initGeometry() {
    const geometry = new THREE.PlaneBufferGeometry(this.radius, this.radius)
    return geometry
  }

  // 初始化材质
  _initMaterial() {
    const material = new THREE.MeshBasicMaterial({
      color: new THREE.Color(this.color),
      depthWrite: false,
      depthTest: true,
      transparent: true,
      side: THREE.FrontSide,
      blending: THREE.NormalBlending,
      opacity: this.opacity
    })

    return material
  }

  // 销毁对象,清理内存
  destroy() {
    this._disposeHierarchy(this.entity, this._dispose)
    this.viewer.world.remove(this.entity)
    this.entity = null
  }
}
